package com.zlzlib.libdata.util;

import android.content.Context;
import android.text.TextUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 * Created by zlz on 2018/6/7.
 * 一些文件操作工具
 */
public class MyFileUtil {

    /**
     * 创建一个文件 如果文件不存在
     *
     * @param path 地址
     */
    public static File createNewFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    public static File createNewFile(String path, String name) {
        File file = new File(path, name);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    /**
     * 创建一个文件夹 如果不存在
     *
     * @param path
     */
    public static File createNewDri(String path) {
        File file = new File(path);
        if (!file.exists()) {
            try {
                file.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    /**
     * 复制单个文件
     *
     * @param oldPath  String 原文件路径 如：c:/fqf.txt
     * @param newPath  String 复制后路径 如：f:/fqf.txt
     * @param listener 复制成功或失败的回调
     */
    public static void copyFileNotThread(final String oldPath, final String newPath, final CopyListener listener) {
        try {
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1024];
                while ((byteread = inStream.read(buffer)) != -1) {
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
            if (null != listener) listener.complete();
        } catch (Exception e) {
            if (null != listener) listener.fail();
        }
    }

    /**
     * 复制单个文件
     *
     * @param oldPath  String 原文件路径 如：c:/fqf.txt
     * @param newPath  String 复制后路径 如：f:/fqf.txt
     * @param listener 复制成功或失败的回调
     */
    public static void copyFile(final String oldPath, final String newPath, final CopyListener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                copyFileNotThread(oldPath, newPath, listener);
            }
        }).start();
    }

    public interface CopyListener {
        void fail();

        void complete();
    }

    /**
     * 递归删除整个文件或文件夹
     *
     * @param dir
     */
    public static void deleteDirOrFile(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete(); // 删除所有文件
            else if (file.isDirectory())
                deleteDirOrFile(file); // 递规的方式删除文件夹
        }
        dir.delete();// 删除目录本身
    }

    /**
     * @param context
     * @param name
     * @return 读取assets 里面的文件转为字符串
     */
    public static String readAssets(Context context, String name) {
        return readAssets(context, name, "GBK");
    }

    /**
     * @Desc: 读取assets 里面的文件转为字符串
     * @DateTime: 2020/2/5 17:16
     * @Author zlz
     */
    public static String readAssets(Context context, String name, String charset) {
        String read = "";
        try {
            read = readTextFromStream(context.getResources().getAssets().open(name), charset).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return read;
    }

    /**
     * @param input
     * @param charset
     * @return 读取流里面的数据
     */
    public static StringBuilder readTextFromStream(InputStream input, String charset) {
        BufferedReader read;
        String line = "";
        StringBuilder sb = new StringBuilder();
        try {
            read = new BufferedReader(new InputStreamReader(input, charset));
            while ((line = read.readLine()) != null) {
                sb.append(line);
            }
            read.close();
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb;
    }

    /**
     * @param path
     * @param fileName
     * @param buffer
     * @param isAppend 是否覆盖之前的
     * @return 存储文件到本地
     */
    public static File saveFile(String path, String fileName, byte[] buffer, boolean isAppend) {
        try {
            File file = createNewFile(path, fileName);
            FileOutputStream out = new FileOutputStream(file, isAppend);
            out.write(buffer);
            out.flush();
            out.close();
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param path
     * @param fileName
     * @param buffer
     * @return 存储文件到本地
     */
    public static File saveFile(String path, String fileName, byte[] buffer) {
        return saveFile(path, fileName, buffer, false);
    }


    //过滤在mac上压缩时自动生成的__MACOSX文件夹
    private static final String MAC_IGNORE = "__MACOSX/";

    /**
     * zip文件解压
     *
     * @param target 解压生成的文件
     * @param source 需要解压的文件
     */
    public static void decompressZipFile(String target, String source) {
        if (TextUtils.isEmpty(target)) {
            return;
        }
        try {
            File file = new File(source);
            if (!file.exists()) {
                return;
            }
            ZipFile zipFile = new ZipFile(file);
            ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(file));
            ZipEntry zipEntry = null;
            while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                String fileName = zipEntry.getName();
                if (fileName != null && fileName.contains(MAC_IGNORE)) {
                    continue;
                }
                File temp = new File(target + File.separator + fileName);
                if (zipEntry.isDirectory()) {
                    File dir = new File(target + File.separator + fileName);
                    dir.mkdirs();
                    continue;
                }
                if (temp.getParentFile() != null && !temp.getParentFile().exists()) {
                    temp.getParentFile().mkdirs();
                }
                byte[] buffer = new byte[1024];
                OutputStream os = new FileOutputStream(temp);
                // 通过ZipFile的getInputStream方法拿到具体的ZipEntry的输入流
                InputStream is = zipFile.getInputStream(zipEntry);
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    os.write(buffer, 0, len);
                }
                os.close();
                is.close();
            }
            zipInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
